Pyramid Of Doom (programming)
   HOME

TheInfoList



OR:

In
computer programming Computer programming or coding is the composition of sequences of instructions, called computer program, programs, that computers can follow to perform tasks. It involves designing and implementing algorithms, step-by-step specifications of proc ...
, a common challenge facing systems programmers is that before an operation can be performed, a number of conditions must first be checked to confirm that the operation can be successfully performed. For example, before data can be written to a file, it must be confirmed that 1) the program has the file open for writing; 2) the program has the necessary permissions to write the data; 3) the data to be written is available; 4) the data to be written is of a valid size. A failure at any of these steps means that the write operation cannot be completed and an error should be returned to the calling program. There are several ways that these multiple required tests can be written in the source code. One way is to check each condition in turn and if a condition fails,
return Return may refer to: In business, economics, and finance * Return on investment (ROI), the financial gain after an expense. * Rate of return, the financial term for the profit or loss derived from an investment * Tax return, a blank document or t ...
from the subroutine at that point, indicating an error condition exists. This style of coding has the disadvantage that the subroutine returns from multiple (possibly many) points and some coding standards discourage having multiple return points. Another way to is to check each condition and if the condition succeeds, enter a deeper
block Block or blocked may refer to: Arts, entertainment and media Broadcasting * Block programming, the result of a programming strategy in broadcasting * W242BX, a radio station licensed to Greenville, South Carolina, United States known as ''96.3 ...
of code that checks the next condition and so on. The deepest enclosing block of code is only reached if all of the precondition tests are successful. This style of coding has the disadvantage that the indentation level increases with every test performed. If many tests are required, the enclosed blocks of code can march off the page to the right margin. This typographical effect is referred to as the pyramid of doom. For example, the pyramid of doom is commonly seen when checking for
null pointer In computing, a null pointer (sometimes shortened to nullptr or null) or null reference is a value saved for indicating that the Pointer (computer programming), pointer or reference (computer science), reference does not refer to a valid Object (c ...
s or handling
callbacks In computer programming, a callback is a function that is stored as data (a reference) and designed to be called by another function often ''back'' to the original abstraction layer. A function that accepts a callback parameter may be design ...
. Two examples of the term are related to a particular programming style in early versions of
JavaScript JavaScript (), often abbreviated as JS, is a programming language and core technology of the World Wide Web, alongside HTML and CSS. Ninety-nine percent of websites use JavaScript on the client side for webpage behavior. Web browsers have ...
, and the nesting of if statements that occurs in
object-oriented programming Object-oriented programming (OOP) is a programming paradigm based on the concept of '' objects''. Objects can contain data (called fields, attributes or properties) and have actions they can perform (called procedures or methods and impl ...
languages when one of the objects may be a null pointer.


Examples

Most modern
object-oriented programming language Object-oriented programming (OOP) is a programming paradigm based on the concept of '' objects''. Objects can contain data (called fields, attributes or properties) and have actions they can perform (called procedures or methods and impleme ...
s use a coding style known as dot notation that allows multiple method calls to be written in a single line of code, each call separated by a period. For instance: theWidth = windows("Main").views(5).size().width(); This code contains four different instructions; it first looks in the collection of windows for a window with the name "Main", then looks in that window's views collection for the 5th subview within it, then calls the size method to return a structure with the view's dimensions, and finally calls the width method on that structure to produce a result that is assigned to a variable name theWidth. The problem with this approach is that the code assumes that all of these values exist. While it is reasonable to expect that a window will have a size and that size will have a width, it is not at all reasonable to assume that a window named "Main" will exist, nor that it has five subviews. If either of those assumptions is wrong, the corresponding call will result in a null pointer error. To avoid this error, the programmer has to check every method call to ensure it returns a value. A safer version of the same code would be: if windows.contains("Main") If the programmer wishes to use that value based on whether or not it exists and is valid, the functional code inside the if statements is all pushed to the right, making it difficult to read longer lines. This often leads to attempts to "flatten" the code: if windows.contains("Main") if theWindow != null && theWindow.views.contains(5) if theView != null Or alternatively: if !windows.contains("Main") else if !windows("Main").views.contains(5) else This sort of programming construct is very common and a number of programming languages have added some sort of
syntactic sugar In computer science, syntactic sugar is syntax within a programming language that is designed to make things easier to read or to express. It makes the language "sweeter" for human use: things can be expressed more clearly, more concisely, or in an ...
to address this. For instance, Apple's
Swift Swift or SWIFT most commonly refers to: * SWIFT, an international organization facilitating transactions between banks ** SWIFT code * Swift (programming language) * Swift (bird), a family of birds It may also refer to: Organizations * SWIF ...
added the concept of optional chaining in if statements while Microsoft's C# 6.0 and
Visual Basic Visual Basic is a name for a family of programming languages from Microsoft. It may refer to: * Visual Basic (.NET), the current version of Visual Basic launched in 2002 which runs on .NET * Visual Basic (classic), the original Visual Basic suppo ...
14 added the null-conditional operators ?. and ? JavaScript JavaScript (), often abbreviated as JS, is a programming language and core technology of the World Wide Web, alongside HTML and CSS. Ninety-nine percent of websites use JavaScript on the client side for webpage behavior. Web browsers have ...
added support for the optional chaining operator in 2020. The basic idea is to allow a string of method calls to immediately return null if any of its members is null, so for instance: theWidth = windows("Main")?.views(5)?.size.width; would assign null to theWidth if either "Main" or the fifth subview is missing, or complete the statement and return the width if they are both valid. There are many times where the programmer wants to take different actions in these two cases, so Swift adds another form of syntactic sugar for this role, the if let statement, also known as "optional binding": if let theView = windows("Main")?.views(5)


Resolution

Pyramid of Doom can usually be resolved in any language by simply breaking up the code into multiple nested functions (or other groupings). For instance, instead of: main() You can break up the functionality like this: doSomething() CC() main() Similarly, data structures can be broken up by levels, when similar pyramids occur. Not only is the Pyramid of Doom solved, but it's better practice to not have large, complicated functions; smaller ones are easier for a programmer to write without erring, easier to read, and easier to verify. Choosing function names for each of these levels will also help the author clarify to readers what is done where. Typically, each level doesn't need many connections to levels that are far away, so separating them out is easy. If there are such connections, the author can re-think their design to something more reliable, because this is a fertile source of bugs.


See also

* Promises, a technique for avoiding the pyramid of doom, e.g. used in JavaScript * Futures and promises">Promises, a technique for avoiding the pyramid of doom, e.g. used in JavaScript *Law of Demeter * Safe navigation operator">Law of Demeter">Futures and promises">Promises, a technique for avoiding the pyramid of doom, e.g. used in JavaScript *Law of Demeter * Safe navigation operator, a programming language operator that lets one avoid the pyramid of doom


References

{{reflist Programming constructs